<template>
  <div class="app-container">
    <!-- 查询 -->
    <div class="filter-container">
      <el-row :gutter="0">
        <el-col :xs="24" :sm="12">
          <el-select class="filter-item" v-model="query.xueke_id" placeholder="请选择学科">
            <el-option v-for="item in xuekes" :key="item.xueke_id" :label="item.xueke_name" :value="item.xueke_id">
            </el-option>
          </el-select>
          <el-select class="filter-item" v-model="query.banji_id" placeholder="请选择班级">
            <el-option v-for="item in banjis" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
          <el-button class="filter-item" type="primary" @click="search()">查询</el-button>
          <el-button class="filter-item" @click="refresh()">刷新</el-button>
        </el-col>
        <el-col :xs="24" :sm="12" style="text-align:right;">
          <el-button class="filter-item" @click="tongji()" icon="el-icon-circle-plus">统计名次与标准分</el-button>
          <el-button class="filter-item" @click="importExcel()" icon="el-icon-circle-plus">导入</el-button>
          <el-button class="filter-item" @click="handleDelete()" type="danger" icon="el-icon-delete">批量删除</el-button>
          <el-button class="filter-item" type="primary" @click="add()">添加</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- 列表 -->
    <el-table ref="multipleTable" v-loading="loading" :data="datas" :height="height" style="width: 100%" border @sort-change="sort" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" min-width="100" sortable="custom" />
      <el-table-column prop="student_xh" label="学号" min-width="100" sortable="custom" />
      <el-table-column prop="student_name" label="姓名" min-width="100" sortable="custom" />
      <el-table-column prop="banji_name" label="班级" min-width="100" sortable="custom" />
      <el-table-column prop="xueke_name" label="学科" min-width="100" sortable="custom" />
      <el-table-column prop="fenshu" label="分数" min-width="100" sortable="custom" />
      <el-table-column prop="mc_banji" label="班内名次" min-width="100" sortable="custom" />
      <el-table-column prop="mc_school" label="校内名次" min-width="100" sortable="custom" />
      <el-table-column prop="tscore" label="标准分" min-width="100" sortable="custom" />
<!--      <el-table-column prop="dengdi" label="等第" min-width="100" sortable="custom" />
      <el-table-column prop="fenshu_zhuguang" label="主观题分数" min-width="100" sortable="custom" />
      <el-table-column prop="fenshu_keguang" label="客观题分数" min-width="100" sortable="custom" /> -->

      <el-table-column label="操作" min-width="100" align="right" fixed="right">
        <template slot-scope="{ row }">
          <el-button size="mini" type="success" @click="edit(row)">修改</el-button>
          <el-button size="mini" type="danger" @click="del(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="count > 0" :total="count" :page.sync="query.page" :limit.sync="query.limit"
      @pagination="list" />
    <!-- 添加、修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialog" top="1vh" :before-close="cancel">
      <el-form ref="ref" :rules="rules" :model="model" label-width="100px" class="dialog-body"
        :style="{height:height+30+'px'}">
        <el-form-item label="学科" prop="xueke_id">
          <el-input v-model="model.xueke_id" placeholder="请输入学科" clearable />
        </el-form-item>
        <el-form-item label="学生" prop="student_id">
          <el-input v-model="model.student_id" placeholder="请输入学生" clearable />
        </el-form-item>
        <el-form-item label="考生" prop="kaosheng_id">
          <el-input v-model="model.kaosheng_id" placeholder="请输入考生" clearable />
        </el-form-item>
        <el-form-item label="班级" prop="banji_id">
          <el-input v-model="model.banji_id" placeholder="请输入班级" clearable />
        </el-form-item>
        <el-form-item label="考试" prop="kaoshi_id">
          <el-input v-model="model.kaoshi_id" placeholder="请输入考试" clearable />
        </el-form-item>
        <el-form-item label="主观题分数" prop="fenshu_zhuguang">
          <el-input v-model="model.fenshu_zhuguang" placeholder="请输入主观题分数" clearable />
        </el-form-item>
        <el-form-item label="客观题分数" prop="fenshu_keguang">
          <el-input v-model="model.fenshu_keguang" placeholder="请输入客观题分数" clearable />
        </el-form-item>
        <el-form-item label="校内名次" prop="mc_school">
          <el-input v-model="model.mc_school" placeholder="请输入校内名次" clearable />
        </el-form-item>
        <el-form-item label="班内名次" prop="mc_banji">
          <el-input v-model="model.mc_banji" placeholder="请输入班内名次" clearable />
        </el-form-item>
        <el-form-item label="标准分" prop="tscore">
          <el-input v-model="model.tscore" placeholder="请输入标准分" clearable />
        </el-form-item>
        <el-form-item label="等第" prop="dengdi">
          <el-input v-model="model.dengdi" placeholder="请输入等第" clearable />
        </el-form-item>
        <el-form-item label="分数" prop="fenshu">
          <el-input v-model="model.fenshu" placeholder="请输入分数" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="importDialogTitle" :visible.sync="importDialog" top="1vh" :before-close="importCancel">
      <el-form ref="ref" label-width="200px" class="dialog-body" :style="{height:height+30+'px'}">
        <el-form-item label="成绩导入模板下载" prop="remark">
          <el-button @click="download">导入模板下载</el-button>
        </el-form-item>
        <el-form-item label="成绩导入" prop="remark">
          <el-upload name="excel_file" :show-file-list="false" :before-upload="uploadBefore" :action="uploadAction"
            :headers="uploadHeaders" :data="uploadData" :on-success="uploadSuccess" :on-error="uploadError">
            <el-button type="primary">导入</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import screenHeight from '@/utils/screen-height'
  import Pagination from '@/components/Pagination'
  import {
    getUserId,
    getToken
  } from '@/utils/auth'
  import {
    list,
    info,
    add,
    edit,
    del,
    download,
    tongji,
    listBanjisByKaoshiId,
    listKaoshiXuekes,
    multiDelete
  } from '@/api/kaoshi_chengji'

  export default {
    name: 'KaoshiChengji',
    components: {
      Pagination
    },
    props: ['kaoshi_id', 'kaoshi_name'],
    data() {
      return {
        height: 680,
        loading: false,
        datas: [],
        count: 0,
        query: {
          page: 1,
          limit: 13,
          xueke_id: '',
          banji_id: ''
        },
        xuekes: [],
        banjis: [],
        dialog: false,
        dialogTitle: '',
        model: {
          id: '',
          xueke_id: '',
          student_id: '',
          kaosheng_id: '',
          banji_id: '',
          kaoshi_id: '',
          fenshu_zhuguang: '',
          fenshu_keguang: '',
          mc_school: '',
          mc_banji: '',
          tscore: '',
          dengdi: '',
          fenshu: '',
        },
        rules: {
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
        },
        importDialog: false,
        importDialogTitle: '',
        uploadAction: process.env.VUE_APP_BASE_API + '/chengji/KaoshiChengji/import',
        uploadHeaders: {
          UserId: getUserId(),
          Token: getToken()
        },
        uploadData: {
          user_id: getUserId(),
          kaoshi_id: this.kaoshi_id
        }
      }
    },
    created() {
      this.height = screenHeight()
      this.list()
      this.listBanjisByKaoshiId()
      this.listKaoshiXuekes()
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      handleDelete() {
        let checkArr = this.multipleSelection;   // multipleSelection存储了勾选到的数据
        let params = [];
        let self = this;
        checkArr.forEach(function (item) {
          params.push(item.id);       // 添加所有需要删除数据的id到一个数组，post提交过去
        });
        this.loading = true
        multiDelete({ids:params}).then(res=>{
          this.$refs.multipleTable.clearSelection();
          this.list();
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      listKaoshiXuekes() {
        listKaoshiXuekes({
          kaoshi_id: this.kaoshi_id
        }).then(res => {
          this.xuekes = res.data;
          console.log(this.xuekes)
        }).catch(() => {
          this.loading = false
        })
      },
      listBanjisByKaoshiId() {
        listBanjisByKaoshiId({
          kaoshi_id: this.kaoshi_id
        }).then(res => {
          this.banjis = res.data;
        }).catch(() => {
          this.loading = false
        })
      },
      // 列表
      list() {
        this.loading = true
        this.query.kaoshi_id = this.kaoshi_id
        list(this.query).then(res => {
          this.datas = res.data.list
          this.count = res.data.count
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      },
      // 添加
      add() {
        this.dialog = true
        this.dialogTitle = '添加'
        this.reset()
      },
      edit(row) {
        this.dialog = true
        this.dialogTitle = '修改：' + row.id
        info({
          id: row.id
        }).then(res => {
          this.reset(res.data)
        })
      },
      // 删除
      del(row) {
        this.$confirm(
          '确定要删除 <span style="color:red">' + row.name + ' </span>吗？',
          '删除：' + row.id, {
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        ).then(() => {
          this.loading = true
          del({
            id: row.id
          }).then(res => {
            this.reset()
            this.list()
            this.$message.success(res.msg)
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {})
      },
      // 取消
      cancel() {
        this.dialog = false
        this.reset()
      },
      // 提交
      submit() {
        this.$refs['ref'].validate(valid => {
          if (valid) {
            this.loading = true
            if (this.model.id) {
              edit(this.model).then(res => {
                this.list()
                this.reset()
                this.dialog = false
                this.$message.success(res.msg)
              }).catch(() => {
                this.loading = false
              })
            } else {
              add(this.model).then(res => {
                this.list()
                this.reset()
                this.dialog = false
                this.$message.success(res.msg)
              }).catch(() => {
                this.loading = false
              })
            }
          }
        })
      },
      // 重置
      reset(row) {
        if (row) {
          this.model = row
        } else {
          this.model = this.$options.data().model
        }
        if (this.$refs['ref'] !== undefined) {
          this.$refs['ref'].resetFields()
        }
      },
      // 查询
      search() {
        this.query.page = 1
        this.list()
      },
      // 刷新
      refresh() {
        this.query = this.$options.data().query
        this.list()
      },
      sort(sort) {
        this.query.sort_field = sort.prop
        this.query.sort_type = ''
        if (sort.order === 'ascending') {
          this.query.sort_type = 'asc'
          this.list()
        }
        if (sort.order === 'descending') {
          this.query.sort_type = 'desc'
          this.list()
        }
      },
      importExcel() {
        this.importDialog = true
        this.importDialogTitle = '导入'
      },
      uploadBefore(file) {
        this.loading = true
      },
      uploadSuccess(res, file) {
        if (res.code === 200) {
          this.loading = false
          this.$message.success(res.msg)
          this.importDialog = false
          this.list()
        } else {
          this.loading = false
          this.$message.error(res.msg)
        }
      },
      uploadError(error) {
        this.loading = false
        console.log(error)
      },
      importCancel() {
        this.importDialog = false
      },
      tongji() {
        this.loading = true
        tongji({
          kaoshi_id: this.kaoshi_id
        }).then(response => {
          this.$message.success(response.msg)
          this.list()
        }).catch(function(error) {
          console.log(error);
          this.loading = false
        });
      },
      download() {
        download().then(response => {
          this.downloadFile(response);
          this.$message.success(response.msg)
        }).catch(function(error) {
          console.log(error);
        });
      },
      // 下载文件
      downloadFile(data) {
        if (!data) {
          return
        }
        let blob = new Blob([data])
        let fileName = '成绩导入模板.xlsx'
        if ('download' in document.createElement('a')) { // 不是IE浏览器
          let url = window.URL.createObjectURL(blob)
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        } else { // IE 10+
          window.navigator.msSaveBlob(blob, fileName)
        }
      }
    }
  }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
